package threadtest;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * BlockingQueue 实现生产者消费者
 */
public class BlockingQueueDemo {
    public static void main(String[] args) {
        BlockingQueueTest blockingQueueTest = new BlockingQueueTest();
        for (int i = 0; i < 30; i++) {
            new Thread(blockingQueueTest::product, "product:" + i).start();
            new Thread(blockingQueueTest::consumer, "consumer:" + i).start();
        }
    }
}

class BlockingQueueTest {
    private ReentrantLock reentrantLock = new ReentrantLock();
    private Condition condition = reentrantLock.newCondition();
    private BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>(20);
    Random random = new Random();

    public void product() {
        try {
            reentrantLock.lock();
            if (!blockingQueue.isEmpty()) {
                condition.await();
            }
            int number = random.nextInt(100) + 1;
            blockingQueue.add(number);
            System.out.println(Thread.currentThread().getName() + "--> 生产者打印：" + number);
            condition.signalAll();
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            reentrantLock.unlock();
        }
    }

    public void consumer() {
        try {
            reentrantLock.lock();
            if (blockingQueue.isEmpty()) {
                condition.await();
            }
            Integer take = blockingQueue.poll();
            System.out.println(Thread.currentThread().getName() + "---> 消费者打印：" + take);
            condition.signalAll();
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            reentrantLock.unlock();
        }
    }
}
